<?php
/**
 * 银行卡验证器
 */
namespace app\api\validate;

use think\Validate;
use think\Db;

class CardValidate extends Validate
{
    protected $rule = [
        'credit_num'      => ['require', 'regex' => '^([1-9]{1})(\d{14}|\d{18})$','checkCard'],
		'credit_name'     => 'require',
		'credit_iden_num' => ['require', 'regex' => '^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$'],
		'credit_mobile'   => ['require', 'regex' => '^1[34578]\d{9}$'],
		'credit_deposit'  => 'require',
		'province'        => 'require|between:1,34',
        'city'            => 'require',
        'area'            => 'require|checkArea',
    ];

    protected $message = [
        'credit_num.require'      => '银行卡必须',
        'credit_num.regex'        => '银行卡错误',
        'credit_name.require'     => '姓名必须',
        'credit_iden_num.require' => '身份证必须',
        'credit_iden_num.regex'   => '身份证错误',
        'credit_mobile.require'   => '手机号必须',
        'credit_mobile.regex'     => '手机号错误',
        'credit_deposit.regex'    => '开户行必须',
        'province.require'        => '省必须选',
        'province.between'        => '省选择错误',
        'city.require'            => '市必须选',
        'area.require'            => '区必须选',
    ];
    /**
     * 验证银行卡是否已经绑定
     */
    public function checkCard($value, $rule ,$data)
    {
    	$is_has = Db::name('credit')->where(['credit_num' => $data['credit_num'], 'is_del' => 1])->find();
    	if (empty($is_has)) {
    		return true;
    	} else {
    		return '银行卡已存在';
    	}
    }
     /**
     * 验证地区
     */
    public function checkArea($value, $rule ,$data)
    {
    	$is_has = Db::name('region')->alias('a')
    			->field('a.*,b.parent_id as grandpa_id')
				->join('region b', 'a.parent_id=b.id', 'left')
				->where(['a.id' => $data['area'], 'a.parent_id' => $data['city'], 'b.parent_id' => $data['province']])
				->find();
	
		if (empty($is_has)) {
			return '请选择正确的地址';
		}
		return true;
    }

}